"""
网络请求：登陆
"""
import requests
import json
from src.config import settings
from src.models.user import User
from src.schemas.login import UserAuth, UserCreate


def login(user_obj: UserAuth):
    """请求登陆"""
    try:
        response = requests.post(
            settings.login_url, data=user_obj.json(), timeout=5)
    except Exception as e:
        return 1001, e
    res = response.json()
    if response.status_code == 200 and res['code'] == 2000:
        new_user_obj = user_obj.dict()
        new_user_obj['token'] = res['data']['token']
        User.update_user(user_obj=new_user_obj)
        return 1000, '登录成功'
    else:
        return 1002, res['message']


def register(user_obj: UserCreate):
    """注册用户"""
    try:
        response = requests.post(
            settings.register_url, data=json.dumps(user_obj.dict(exclude_none=True)), timeout=5)
    except Exception as e:
        return 1001, '网络请求出错'
    res = response.json()
    if response.status_code == 200 and res['code'] == 2000:
        return 1000, '注册成功,请登录!'
    else:
        return res['code'], res['message']


if __name__ == '__main__':
    user_obj = UserAuth(username='yczha@cc.com', password='121561zyc')
    login(user_obj)

    user_obj = UserCreate(
        nickname='ttt', email='yczha@cc.com', password='121561zyc')
    register(user_obj)
